<template>
  <div>消息中心</div>
</template>
<script lang="ts">
import { ElMessage } from "element-plus";
import { defineComponent, reactive, ref, toRefs } from "vue";
import { useRouter } from "vue-router";
import { postUserInfo, updatePassword } from "/@/api/user";
import { storageLocal } from "/@/utils/storage";
import { updateUser } from "/@/api/user";
import NotifMessage from "/@/utils/message/notification";
import JSEncrypt from "jsencrypt";

// import Service from './api/index'

// eslint-disable-next-line no-unused-vars
type VoidNoop = (arg0?: Error) => void;
export default defineComponent({
  name: "PersonalSetting",
  setup() {
    const router = useRouter();
    const tabPosition = ref("left");
    const settingFormRef = ref();
    const passWordFormRef = ref();

    const noticeSwitch = reactive({
      userSwitch: false,
      sysSwitch: true,
      taskSwitch: true
    });
    const settingForm = reactive({
      name: "",
      age: "",
      email: "",
      // password: "",
      phoneNum: ""
    });

    const passWordForm = reactive({
      oldPassword: "",
      password: "",
      passwordTwo: ""
    });

    let isEmp = ref("1");
    const imageUrl = ref();
    const updateLoading = ref(false);

    // eslint-disable-next-line no-unused-vars
    const validateMobile = (rule: any, value: string, callback: VoidNoop) => {
      if (value === "") {
        callback(new Error("手机号码不可为空"));
      } else {
        const reg = /^1[3-9]\d{9}$/;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的手机号码"));
        }
      }
    };

    const validatePassword = (rule: any, value: string, callback: VoidNoop) => {
      if (value === "") {
        callback(new Error("密码不可为空"));
      } else {
        if (value === passWordForm.password) {
          callback();
        } else {
          callback(new Error("两次输入密码不一致"));
        }
      }
    };

    const validateNewPassword = (
      rule: any,
      value: string,
      callback: VoidNoop
    ) => {
      if (value === "") {
        callback(new Error("密码不可为空"));
      } else {
        const reg1 = /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])/;
        const reg2 = /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[-_!@#$&*? ]).*$/;
        const reg3 = /^.*(?=.{6,})(?=.*\d)(?=.*[a-z])(?=.*[-_!@#$&*? ]).*$/;
        const reg4 = /^.*(?=.{6,})(?=.*[A-Z])(?=.*[a-z])(?=.*[-_!@#$&*? ]).*$/;
        const reg5 =
          /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[-_!@#$&*? ]).*$/;
        if (
          reg1.test(value) ||
          reg2.test(value) ||
          reg3.test(value) ||
          reg4.test(value) ||
          reg5.test(value)
        ) {
          callback();
        } else {
          callback(
            new Error(
              "密码长度必须6个字符以上，且至少包含大写字母、小写字母、数字、特殊符号中的任意三项"
            )
          );
        }
      }
    };

    //
    const rules = {
      email: [
        { required: true, message: "请输入邮箱地址", trigger: "blur" },
        {
          type: "email",
          message: "请输入正确的邮箱地址",
          trigger: ["blur", "change"]
        }
      ],
      name: {
        required: true,
        message: "请输入姓名",
        trigger: ["blur", "change"]
      },
      userName: {
        required: true,
        message: "请输入用户名",
        trigger: ["blur", "change"]
      },
      phoneNum: {
        required: true,
        validator: validateMobile,
        trigger: ["blur", "change"]
      }
    };

    const rules2 = {
      oldPassword: {
        required: true,
        message: "请输入原始密码",
        trigger: ["blur", "change"]
      },
      password: {
        required: true,
        validator: validateNewPassword,
        trigger: ["blur", "change"]
      },
      passwordTwo: {
        required: true,
        validator: validatePassword,
        trigger: ["blur", "change"]
      }
    };

    const handleUpdatePassword = () => {
      passWordFormRef.value.validate(async (valid: any) => {
        if (valid) {
          try {
            const encryptor = new JSEncrypt(); // 创建加密对象实例
            let publickKey = `MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKcbECgXDZ/989X8TuAFfQpDUi0i5n7EZpwGvbETXLXtHunS1SPDbLlrlYjSaF9bAAdf5SsPtkOyoQJALMw24AkCAwEAAQ==`;

            // 生产环境的密钥
            // 生产环境的密钥
            if (import.meta.env.VITE_PROJECT_ENV === "pre") {
              publickKey = `MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOoQrxqdDPj7Yafbp+qDnv4XZ+3J9wP7DTT3Lu1vwOsq
      cMW4x5lo54ROu7VMx1m4iaUxj7L/uApoh2klC4muEx8CAwEAAQ==`;
            }
            const publicPassword = `-----BEGIN PUBLIC KEY-----${publickKey}-----END PUBLIC KEY-----`;
            encryptor.setPublicKey(publicPassword); //设置公钥

            const rsaPassWord1 = encryptor.encrypt(passWordForm.oldPassword); // 对内容进行加密
            const transferPassword1 = btoa(rsaPassWord1 as string);

            const rsaPassWord2 = encryptor.encrypt(passWordForm.password); // 对内容进行加密
            const transferPassword2 = btoa(rsaPassWord2 as string);
            const params = {
              oldPassword: transferPassword1,
              password: transferPassword2
            };
            const { code, data, message } = await updatePassword(params);
            console.log(code, data, message);
            if (data) {
              NotifMessage.success(message);
            } else {
              message && NotifMessage.error(message);
            }
          } catch (err) {
            console.error(err);
          }
          // 执行通过校验以后的操作；
          return true;
        }
        return false;
      });
    };

    const goback = () => {
      router.go(-1);
    };
    const submitForm = () => {
      settingFormRef.value.validate(async (valid: any) => {
        if (valid) {
          try {
            const info = storageLocal.getItem("info");
            const params = {
              ...settingForm,
              id: info ? info?.userId : ""
            };
            const { code, data } = await updateUser(params);
            console.log(code, data);
            if (code === 200) {
              const { userId, username, accessToken } =
                storageLocal.getItem("info");
              storageLocal.setItem("info", {
                userId,
                username,
                accessToken,
                name: settingForm.name
              });
              NotifMessage.success("修改成功");
            }
          } catch (err) {
            console.error(err);
          }
          // 执行通过校验以后的操作；
          return true;
        }
        return false;
      });
    };
    const resetForm = () => {
      settingFormRef.value.resetFields();
    };

    const initUserInfo = async () => {
      try {
        const info = storageLocal.getItem("info");
        const params = {
          id: info ? info?.userId : ""
        };
        const { code, data } = await postUserInfo(params);
        if (code === 200) {
          console.log(data);
          settingForm.name = data.name;
          settingForm.age = data.age;
          settingForm.email = data.email;
          settingForm.phoneNum = data.phoneNum;
          isEmp.value = data.isEmp;
        }
      } catch (err) {
        console.log(err);
      }
    };

    initUserInfo();

    const handleAvatarSuccess = (res: any, file: { raw: any }) => {
      imageUrl.value = URL.createObjectURL(file.raw);
    };
    const beforeAvatarUpload = (file: {
      raw: any;
      type: string;
      size: number;
    }) => {
      // const isJPG = file.type === 'image/jpeg'
      if (!/(gif|png|jpg|jpeg)$/i.test(file.type)) {
        ElMessage({
          message: "上传头像图片只能是gif|png|jpg|jpeg 格式!",
          type: "warning"
        });
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        ElMessage.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    };
    return {
      goback,
      isEmp,
      tabPosition,
      settingFormRef,
      passWordFormRef,
      settingForm,
      passWordForm,
      submitForm,
      resetForm,
      handleAvatarSuccess,
      beforeAvatarUpload,
      handleUpdatePassword,
      rules,
      rules2,
      imageUrl,
      ...toRefs(noticeSwitch),
      updateLoading
    };
  }
});
</script>

<style lang="scss" scoped>
.PersonalSetting {
  background: #fcf9f9;
  padding-top: 60px;
  .demo-ruleForm {
    text-align: left;
    width: 500px;
  }
  .set-title {
    text-align: left;
  }
  .secure-item {
    width: 100%;
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    .secure-info {
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      align-items: flex-start;
      .secure-key {
        margin-bottom: 4px;
        color: rgba(0, 0, 0, 0.85);
        font-size: 14px;
        line-height: 1.6;
      }
      .secure-value {
        color: rgba(0, 0, 0, 0.45);
        font-size: 14px;
        line-height: 1.6;
      }
    }
    .opera-btn {
      color: #1890ff;
      cursor: pointer;
    }
  }
  .set-info {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    align-items: flex-start;
    .form-info {
    }
    .avatar {
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      align-items: flex-end;
      .preview {
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        align-items: flex-start;
        margin-right: 20px;
        img {
          width: 174px;
          height: 174px;
          border-radius: 50%;
        }
      }

      .avatar-uploader .el-upload:hover {
        border-color: #409eff;
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
      }
      .avatar {
        width: 178px;
        height: 178px;
        display: block;
      }
    }
  }
  .info {
    text-align: left;
    padding-left: 20px;
    margin-bottom: 20px;
    font-size: 12px;
  }
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .box-card {
    width: 100%;
  }
}
</style>
